from django.contrib.auth.backends import ModelBackend
from .models import User
import re
import logging
logger = logging.getLogger('django')


def jwt_response_payload_handler(token, user=None, request=None):
    # 重写JWT登录视图响应函数
    return {
        'username': user.username,
        'user_id': user.id,
        'token': token
    }


def get_user_by_account(account):
    """
    通过账号判断是用户名或者手机号，并获取user模型对象
    :param account: 传入的账号（手机，用户名）
    :return:
    """
    try:
        if re.match(r'1[3-9]\d{9}', account):
            user = User.objects.get(mobile=account)
            logger.info('mobile login %s' % user.mobile)
        else:
            user = User.objects.get(username=account)
            logger.info('username login %s' % user.username)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    # 修改django中默认的后端登录认证的类ModelBackend中的authenticate方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 获取登录账号
        user = get_user_by_account(username)
        # 验证密码
        if user and user.check_password(password):
            # 返回响应
            return user